import tkinter as tk
from tkinter import messagebox
import pymysql
from 用户界面 import MainPage
from PIL import Image, ImageTk
DBHOST = 'localhost'
DBUSER = 'root'
PASSWORD = 'kongxingli2002'
DBNAME = 'supermarket'


class RegisterPage:
    def __init__(self, master, login_page):
        self.root = master
        self.login_page = login_page

        self.username = tk.StringVar()
        self.password = tk.StringVar()

        self.page2 = tk.Frame(self.root)
        self.page2.pack()

        tk.Label(self.page2, text='注册新账号').grid(row=0, columnspan=2, pady=10)
        tk.Label(self.page2, text='用户名').grid(row=1, column=0)
        tk.Entry(self.page2, textvariable=self.username).grid(row=1, column=1)
        tk.Label(self.page2, text='密码').grid(row=2, column=0)
        tk.Entry(self.page2, textvariable=self.password).grid(row=2, column=1)

        tk.Button(self.page2, text='确认注册', command=self.register).grid(row=3, columnspan=2, pady=20)
        tk.Button(self.page2, text='返回', command=self.return_to_login).grid(row=4, columnspan=2)

    def register(self):
        name = self.username.get()
        pwd = self.password.get()

        if not name:
            messagebox.showinfo('提示', "用户名不能为空，请输入用户名！")
            return
        if not pwd:
            messagebox.showinfo('提示', "密码不能为空，请输入密码！")
            return

        # 将用户名和密码写入数据库
        if self.save_to_db(name, pwd):
            messagebox.showinfo('提示', "注册成功！")
            self.return_to_login()
        else:
            messagebox.showinfo('提示', "注册失败，请稍后再试！")

    def save_to_db(self, username, password):
        try:
            with pymysql.connect(host=DBHOST, user=DBUSER, password=PASSWORD, database=DBNAME) as conn:
                with conn.cursor() as cursor:
                    sql = 'INSERT INTO USERS (账户名, 密码) VALUES (%s, %s)'
                    cursor.execute(sql, (username, password))
                    conn.commit()
                    return True
        except pymysql.MySQLError as e:
            print("数据库错误:", e)
            messagebox.showerror('错误', '注册失败，请稍后再试。')
            return False

    def return_to_login(self):
        self.page2.destroy()
        self.login_page.page1.pack()


class LoginPage:
    def __init__(self, master):
        self.root = master
        self.root.geometry('300x180')
        self.root.title('用户页面')
        self.background_image=Image.open(r"背景图.jpg")
        self.background_photo = ImageTk.PhotoImage(self.background_image)
        #设置背景
        bg_label=tk.Label(self.root,image=self.background_photo)
        bg_label.place(x=0,y=0,relwidth=1,relheight=1)

        self.username = tk.StringVar()
        self.password = tk.StringVar()

        self.page1 = tk.Frame(self.root)
        self.page1.pack()

        tk.Label(self.page1).grid(row=0, column=0)
        tk.Label(self.page1, text='用户名').grid(row=1, column=1)
        tk.Entry(self.page1, textvariable=self.username).grid(row=1, column=2, pady=10)
        tk.Label(self.page1, text='密码').grid(row=2, column=1)
        tk.Entry(self.page1, show='*', textvariable=self.password).grid(row=2, column=2)

        tk.Button(self.page1, text='登录', command=self.login).grid(row=3, column=1, pady=30)
        tk.Button(self.page1, text='注册', command=self.register_page).grid(row=3, column=2, pady=30)
        tk.Button(self.page1, text='返回', command=self.page1.quit).grid(row=3, column=3)

    def login(self):
        name = self.username.get()
        pwd = self.password.get()

        if not name:
            messagebox.showinfo('提示', "用户名不能为空，请输入账号！")
            return
        if not pwd:
            messagebox.showinfo('提示', "密码不能为空，请输入密码！")
            return

        login_successful = self.login_verify(name, pwd)
        if login_successful:
            self.page1.destroy()
            MainPage(self.root)
        else:
            messagebox.showinfo('提示', "用户名或密码错误，请重新输入！")
            self.password.set('')

    def login_verify(self, username, password):
        return self.login_db(username, password)

    def login_db(self, username, password):
        try:
            with pymysql.connect(host=DBHOST, user=DBUSER, password=PASSWORD, database=DBNAME) as conn:
                with conn.cursor() as cursor:
                    sql = 'SELECT * FROM USERS WHERE 账户名=%s AND 密码=%s'
                    cursor.execute(sql, (username, password))
                    result = cursor.fetchall()
                    conn.commit()
                    return len(result) > 0
        except pymysql.MySQLError as e:
            print("数据库连接错误:", e)
            messagebox.showerror('错误', '无法连接到数据库，请稍后再试。')
            return False

    def register_page(self):
        self.page1.pack_forget()  # 隐藏登录界面
        RegisterPage(self.root, self)

if __name__ == '__main__':
    root = tk.Tk()
    LoginPage(master=root)
    root.mainloop()